<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="20" :xs="24">
        <el-form ref="queryForm" :model="queryParams" :inline="true" label-width="68px">
          <el-form-item label="用户名称" prop="userName">
            <el-input
              v-model="queryParams.userName"
              placeholder="请输入用户名称"
              clearable
              size="small"
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="手机号码" prop="phonenumber">
            <el-input
              v-model="queryParams.phonenumber"
              placeholder="请输入手机号码"
              clearable
              size="small"
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="用户状态" prop="status">
            <el-select v-model="queryParams.status" placeholder="用户状态" clearable size="small" style="width: 240px">
              <el-option v-for="dict in statusOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
            </el-select>
          </el-form-item>
          <el-form-item label="创建时间">
            <el-date-picker
              v-model="dateRange"
              size="small"
              style="width: 240px"
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
            >新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="el-icon-edit"
              size="mini"
              :disabled="single"
              @click="handleUpdate"
            >修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
            >删除</el-button>
          </el-col>
        </el-row>
      </el-col>
      <el-table :data="userList" style="width: 100%" :row-class-name="tableRowClassName" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column key="id" prop="id" label="用户编号" align="center" />
        <el-table-column key="userName" prop="userName" label="用户名称" align="center" />
        <el-table-column key="sex" prop="sex" label="性别" align="center" />
        <el-table-column key="email" prop="email" label="邮箱" align="center" />
        <el-table-column key="phonenumber" prop="phonenumber" label="手机号" align="center" />
        <el-table-column key="status" prop="status" label="状态" align="center" />
        <el-table-column key="createTime" prop="createTime" label="创建时间" align="center" />
        <el-table-column label="操作" align="center" width="160" class-name="small-padding fixed-width">
          <template v-if="scope.row.id !== 1" slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getUserList" />
    </el-row>
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item v-if="form.id == undefined" label="用户名称" prop="userName">
              <el-input v-model="form.userName" placeholder="请输入用户名称" maxlength="30" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="form.id == undefined" label="密码" prop="password">
              <el-input v-model="form.password" placeholder="请输入密码" maxlength="20" show-password />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="性别">
              <el-select v-model="form.sex" placeholder="请选择">
                <el-option v-for="dict in sexOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-radio-group v-model="form.status">
                <el-radio v-for="dict in statusOptions" :key="dict.dictValue" :label="dict.dictLabel">{{ dict.dictLabel }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="手机号" prop="phonenumber">
              <el-input v-model="form.phonenumber" placeholder="请输入手机号" maxlength="11" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="form.email" placeholder="请输入邮箱" maxlength="30" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="角色">
              <el-select v-model="form.roleIds" multiple placeholder="请选择">
                <el-option v-for="item in roleOptions" :key="item.id" :label="item.roleName" :value="item.id" :disabled="item.status==1" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确定</el-button>
        <el-button @click="cancel">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<style>
.el-table .warning-row {
  background: oldlace;
}
.el-table .success-row {
  background: #f0f9eb;
}
</style>
<script>
import { listUser, addUser, updateUser, getUserInfo, delUserInfo } from '@/api/user'
import { getDictInfo } from '@/api/dict'
export default {
  data() {
    return {
      userList: null,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: undefined,
        phonenumber: undefined,
        status: undefined,
        beginDate: '',
        endDate: ''
      },
      total: 0,
      title: '',
      form: {},
      open: false,
      single: true,
      multiple: true,
      sexOptions: [],
      statusOptions: [],
      roleOptions: [],
      dateRange: [],
      dictType: '',
      rules: {
        userName: [
          {
            required: true,
            message: '用户名称不能为空',
            trigger: 'blur'
          },
          {
            min: 2,
            max: 20,
            message: '用户名称长度必须介于 2 和 20 之间',
            trigger: 'blur'
          }
        ],
        password: [
          {
            required: true,
            message: '用户名称不能为空',
            trigger: 'blur'
          },
          {
            min: 6,
            max: 20,
            message: '用户密码长度必须介于 6 和 20 之间',
            trigger: 'blur'
          }
        ],
        email: [
          {
            type: 'email',
            message: '请输入正确的邮箱地址',
            trigger: ['blur', 'change']
          }
        ],
        phonenumber: [
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: '请输入正确的手机号码',
            trigger: 'blur'
          }
        ]
      },
      ids: []
    }
  },
  created() {
    this.getUserList()
    this.getDictSexInfo()
    this.getDictStatusInfo()
  },
  methods: {
    tableRowClassName({ row, rowIndex }) {
      if (rowIndex === 1) {
        return 'warning-row'
      } else if (rowIndex === 3) {
        return 'success-row'
      }
      return ''
    },
    getUserList() {
      listUser(this.queryParams).then((response) => {
        this.userList = response.data.records
        this.total = response.data.total
      })
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.queryParams.beginDate = this.dateRange[0]
      this.queryParams.endDate = this.dateRange[1]
      this.getUserList()
    },
    resetQuery() {
      this.dateRange = []
      this.resetForm('queryForm')
      this.handleQuery()
    },
    handleAdd() {
      this.reset()
      getUserInfo(0).then(response => {
        this.roleOptions = response.data.roles
        this.open = true
        this.title = '添加用户'
      })
    },
    handleUpdate(row) {
      this.reset()
      const userId = row.id || this.ids
      getUserInfo(userId).then(response => {
        this.form = response.data.userInfo
        this.roleOptions = response.data.roles
        this.form.roleIds = response.data.roleIds
        this.open = true
        this.title = '修改用户'
        this.form.password = ''
      })
    },
    handleDelete(row) {
      const userIds = row.id || this.ids
      this.$confirm('是否确认删除用户编号为[' + userIds + ']的数据?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return delUserInfo(userIds)
      }).then(() => {
        this.getUserList()
        this.msgSuccess('删除成功!')
      }).catch(() => {})
    },
    getDictSexInfo() {
      this.dictType = 'sys-user-sex'
      getDictInfo(this.dictType).then(response => {
        this.sexOptions = response.data
      })
    },
    getDictStatusInfo() {
      this.dictType = 'sys-user-status'
      getDictInfo(this.dictType).then(response => {
        this.statusOptions = response.data
      })
    },
    submitForm: function() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id === undefined) {
            addUser(this.form).then(response => {
              this.msgSuccess('新增成功')
              this.open = false
              this.getUserList()
            })
          } else {
            console.log('进入修改')
            updateUser(this.form).then(response => {
              console.log('返回信息' + JSON.stringify(response))
              this.msgSuccess('修改成功')
              this.open = false
              this.getUserList()
            })
          }
        }
      })
    },
    cancel() {
      this.open = false
      this.reset()
    },
    reset() {
      this.form = {
        id: undefined,
        userName: undefined,
        password: undefined,
        phonenumber: undefined,
        email: undefined,
        sex: undefined,
        status: undefined
      }
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    }
  }
}
</script>
